<template>
  <view class="container" v-if="isLoaded">
    <!-- 加载中提示 -->
    <view class="loading-container" v-if="!isLoaded">
      <view class="loading-spinner"></view>
      <text class="loading-text">加载中...</text>
    </view>
    <!-- 顶部状态栏 -->
    <view class="status-bar" :class="getStatusClass(orderInfo.order_status)">
      <text class="status-text">{{ orderInfo.statusText }}</text>
      <text class="status-desc">{{ getStatusDesc(orderInfo.order_status) }}</text>
    </view>

    <!-- 收货地址信息 -->
    <view class="address-card">
      <view class="address-icon">
        <uni-icons type="location" size="22" color="#ff6700"></uni-icons>
      </view>
      <view class="address-content">
        <view class="address-user">
          <text class="user-name">{{ orderInfo.address.user_name }}</text>
          <text class="user-phone">{{ orderInfo.address.tel_number }}</text>
        </view>
        <view class="address-detail">
          {{ orderInfo.address.province_name + orderInfo.address.city_name + orderInfo.address.county_name + orderInfo.address.detail_info }}
        </view>
      </view>
    </view>

    <!-- 商品信息 -->
    <view class="goods-card">
      <view class="goods-header">
        <text class="goods-title">商品信息</text>
      </view>
      <view class="goods-content">
        <view class="goods-item">
          <image class="goods-image" :src="baseUrl + orderInfo.goods.cover" mode="aspectFill"></image>
          <view class="goods-info">
            <text class="goods-name">{{ orderInfo.goods.goods_name }}</text>
            <text class="goods-spec" v-for="(spec, index) in orderInfo.orderSpecifications" :key="index">
              {{ spec.speci_name }}: {{ spec.speci_value }}
            </text>
            <view class="goods-price-quantity">
              <text class="goods-price">¥{{ orderInfo.goods.price.toFixed(2) }}</text>
              <text class="goods-quantity">x{{ orderInfo.number }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 订单信息 -->
    <view class="order-info-card">
      <view class="card-header">
        <text class="card-title">订单信息</text>
      </view>
      <view class="order-detail-list">
        <view class="order-detail-item">
          <text class="item-label">订单编号</text>
          <view class="item-value-with-copy">
            <text class="item-value">{{ orderInfo.order_id }}</text>
            <button class="copy-btn" @click="copyOrderId">复制</button>
          </view>
        </view>
        <view class="order-detail-item">
          <text class="item-label">下单时间</text>
          <text class="item-value">{{ orderInfo.create_time }}</text>
        </view>
        <view class="order-detail-item" v-if="orderInfo.ali_pay_id">
          <text class="item-label">支付方式</text>
          <text class="item-value">支付宝</text>
        </view>
        <view class="order-detail-item" v-if="orderInfo.ali_pay_id">
          <text class="item-label">支付交易号</text>
          <text class="item-value">{{ orderInfo.ali_pay_id }}</text>
        </view>
        <view class="order-detail-item">
          <text class="item-label">物流状态</text>
          <text class="item-value">{{ orderInfo.logistics_number ? '已发货' : '商品待发货' }}</text>
        </view>
        <view class="order-detail-item" v-if="orderInfo.logistics_number">
          <text class="item-label">物流单号</text>
          <view class="item-value-with-copy">
            <text class="item-value">{{ orderInfo.logistics_number }}</text>
            <button class="copy-btn" @click="copyLogisticsNumber">复制</button>
          </view>
        </view>
      </view>
    </view>

    <!-- 价格信息 -->
    <view class="price-card">
      <view class="price-item">
        <text class="price-label">商品金额</text>
        <text class="price-value">¥{{ Number(orderInfo.should_price || 0).toFixed(2) }}</text>
      </view>
      <view class="price-item">
        <text class="price-label">优惠券</text>
        <text class="price-value discount-value">
          -¥{{ Number(couponAmount || 0).toFixed(2) }}
        </text>
      </view>
      <view class="price-item total-price">
        <text class="price-label">实付款</text>
        <text class="price-value total-value">¥{{ Number(orderInfo.real_price || 0).toFixed(2) }}</text>
      </view>
    </view>

    <!-- 底部操作栏 -->
    <view class="bottom-action-bar">
      <button class="action-btn contact-btn" @click="gotoSmartSevice">联系客服</button>
      <button v-if="orderInfo.order_status === 0" class="action-btn pay-btn" @click="gotoPay">去支付</button>
      <button v-if="orderInfo.order_status === 1" class="action-btn remind-btn" @click="urgeHandle">提醒发货</button>
      <button v-if="orderInfo.order_status === 2" class="action-btn confirm-btn" @click="confirmHadnle">确认收货</button>
      <button v-if="orderInfo.order_status === 4" class="action-btn review-btn">评价商品</button>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';

// 基础URL
const baseUrl = ref(uni.$baseUrl);
// 订单信息 - 初始化所有必要的嵌套对象和属性以避免undefined错误
const orderInfo = ref({
  order_status: 0,
  statusText: '',
  should_price: 0,
  real_price: 0,
  number: 0,
  use_coupon: 0,
  coupon_id: '',
  logistics_number: '',
  order_id: '',
  create_time: '',
  ali_pay_id: '',
  address: {
    user_name: '',
    tel_number: '',
    province_name: '',
    city_name: '',
    county_name: '',
    detail_info: ''
  },
  goods: {
    cover: '',
    goods_name: '',
    price: 0,
    slideshows: []
  },
  orderSpecifications: []
});
// 优惠券信息
const couponInfo = ref(null);
// 优惠金额
const couponAmount = ref(0);

// 获取订单状态描述
const getStatusDesc = (status) => {
  const statusMap = {
    0: '请在15分钟内完成付款，超时订单将自动取消',
    1: '商家正在备货中，请耐心等待',
    2: '商品已发出，请注意查收',
    3: '售后处理中',
    4: '订单已完成',
    5: '订单已取消'
  };
  return statusMap[status] || '';
};

// 获取订单状态样式类
const getStatusClass = (status) => {
  const classMap = {
    0: 'status-pending',
    1: 'status-shipping',
    2: 'status-receiving',
    3: 'status-after-sale',
    4: 'status-completed',
    5: 'status-canceled'
  };
  return classMap[status] || '';
};

// 跳转客服页面
function gotoSmartSevice(){
	uni.navigateTo({
		url: "/subPkg2/smart_service/smart_service"
	})
}

// 确定收货处理器
function confirmHadnle(){
	uni.showToast({
		duration: 2000,
		image: baseUrl + "cat/dancing.gif"
	});
}


// 提醒发货处理器
function urgeHandle(){
	uni.showToast({
		duration: 2000,
		image: baseUrl + "cat/blow.gif"
	});
}

// 复制订单ID
const copyOrderId = () => {
  uni.setClipboardData({
    data: orderInfo.value.order_id,
    success: () => {
      uni.showToast({
        title: '订单号已复制',
        icon: 'success'
      });
    }
  });
};

// 复制物流单号
const copyLogisticsNumber = () => {
  if (orderInfo.value.logistics_number) {
    uni.setClipboardData({
      data: orderInfo.value.logistics_number,
      success: () => {
        uni.showToast({
          title: '物流单号已复制',
          icon: 'success'
        });
      }
    });
  }
};

// 获取优惠券信息
const getCouponInfo = async (couponId) => {
  try {
    const { data: res } = await uni.$http.get(`/coupon/getById/${couponId}`);
    if (res.code === 1 && res.data) {
      couponInfo.value = res.data;
      couponAmount.value = res.data.value || 0;
    }
  } catch (error) {
    console.error('获取优惠券信息失败:', error);
  }
};

// 去付款
const gotoPay = ()=>{
	let item = uni.getStorageSync("view_order");
	
	// 检查订单还在不在支付有效期
	const orderDate = new Date(item.create_time);
	const endDate = new Date(orderDate.getTime() + 15 * 60 * 1000); // 获取支付过期时间戳
	const now = new Date(); // 获取当前时间戳
	const difference = Math.floor((endDate - now) / 1000); // 计算剩余时间差（秒）
	
	if(difference <= 0){
		uni.showToast({
			title: '订单支付超时，已取消',
			icon: "none"
		});
		return 1;
	}
	
	// console.log("订单有效，剩余支付时间：", difference);
	
	// 取出订单ID，传到付款页面
	let orderId = item.order_id;
	
	// 构造规格对象，以适配GoodsCard组件展示
	let tempSpeciObk = [];
	
	for (let specItem of item.orderSpecifications) {
		tempSpeciObk.push({speciName: specItem.speci_name, speciValue: {specis_value: specItem.speci_value}})
	}
	
	// 更改本地存储中的OrderInfo
	let orderInfo = {
		goodsInfo: item.goods,
		address: item.address,
		specifications: tempSpeciObk, // 选择的商品规格
		number: item.number
	}
	
	uni.setStorageSync("orderInfo", JSON.stringify(orderInfo));
	
	// 携带参数，页面跳转
	uni.navigateTo({
		url:`/subPkg2/pay/pay?orderId=${orderId}`
	})
}

// 页面加载时执行
// 加载状态标志
const isLoaded = ref(false);

onMounted(async () => {
  try {
    // 显示加载中提示
    uni.showLoading({
      title: '加载中...'
    });
    
    // 从本地存储获取订单信息
    const orderData = uni.getStorageSync('view_order');
    if (orderData) {
      // 解析数据
      const parsedData = typeof orderData === 'string' ? JSON.parse(orderData) : orderData;
      
      // 安全地更新orderInfo，确保所有必要的嵌套对象存在
      orderInfo.value = {
        ...orderInfo.value,
        ...parsedData,
        address: {
          ...orderInfo.value.address,
          ...(parsedData.address || {})
        },
        goods: {
          ...orderInfo.value.goods,
          ...(parsedData.goods || {})
        },
        orderSpecifications: parsedData.orderSpecifications || []
      };
      
      // 如果使用了优惠券，获取优惠券信息
      if (orderInfo.value.use_coupon === 1 && orderInfo.value.coupon_id) {
        await getCouponInfo(orderInfo.value.coupon_id);
      }
      
      // 标记加载完成
      isLoaded.value = true;
    } else {
      uni.showToast({
        title: '订单信息获取失败',
        icon: 'none'
      });
      setTimeout(() => {
        uni.navigateBack();
      }, 1500);
    }
  } catch (error) {
    console.error('初始化订单详情失败:', error);
    uni.showToast({
      title: '订单信息解析失败',
      icon: 'none'
    });
    setTimeout(() => {
      uni.navigateBack();
    }, 1500);
  } finally {
    // 隐藏加载提示
    uni.hideLoading();
  }
});
</script>

<style lang="scss">
.container {
  padding-bottom: 120rpx;
  background-color: #f5f5f5;
}

/* 顶部状态栏 */
.status-bar {
  padding: 40rpx 30rpx;
  color: #fff;
  background: linear-gradient(135deg, #ff6700, #ff9500);
  
  .status-text {
    font-size: 36rpx;
    font-weight: bold;
    margin-bottom: 10rpx;
    display: block;
  }
  
  .status-desc {
    font-size: 24rpx;
    opacity: 0.9;
  }
  
  &.status-pending {
    background: linear-gradient(135deg, #ff9500, #ffae00);
  }
  
  &.status-shipping {
    background: linear-gradient(135deg, #ff6700, #ff9500);
  }
  
  &.status-receiving {
    background: linear-gradient(135deg, #3c8ce7, #00b4ff);
  }
  
  &.status-after-sale {
    background: linear-gradient(135deg, #9c27b0, #7b1fa2);
  }
  
  &.status-completed {
    background: linear-gradient(135deg, #2ea157, #159957);
  }
  
  &.status-canceled {
    background: linear-gradient(135deg, #909399, #606266);
  }
}

/* 收货地址卡片 */
.address-card {
  display: flex;
  background-color: #fff;
  padding: 30rpx;
  margin: 20rpx;
  border-radius: 12rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
  
  .address-icon {
    margin-right: 20rpx;
    padding-top: 6rpx;
  }
  
  .address-content {
    flex: 1;
    
    .address-user {
      display: flex;
      margin-bottom: 10rpx;
      
      .user-name {
        font-weight: bold;
        margin-right: 30rpx;
        font-size: 30rpx;
      }
      
      .user-phone {
        color: #666;
        font-size: 28rpx;
      }
    }
    
    .address-detail {
      color: #333;
      font-size: 28rpx;
      line-height: 1.5;
    }
  }
}

/* 商品卡片 */
.goods-card {
  background-color: #fff;
  margin: 20rpx;
  border-radius: 12rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
  
  .goods-header {
    padding: 20rpx 30rpx;
    border-bottom: 1rpx solid #eee;
    
    .goods-title {
      font-size: 28rpx;
      font-weight: bold;
      color: #333;
    }
  }
  
  .goods-content {
    padding: 20rpx;
    
    .goods-item {
      display: flex;
      padding: 20rpx 0;
      
      .goods-image {
        width: 160rpx;
        height: 160rpx;
        border-radius: 8rpx;
        background-color: #f5f5f5;
      }
      
      .goods-info {
        flex: 1;
        margin-left: 20rpx;
        position: relative;
        
        .goods-name {
          font-size: 28rpx;
          color: #333;
          line-height: 1.4;
          margin-bottom: 10rpx;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
          overflow: hidden;
        }
        
        .goods-spec {
          display: inline-block;
          font-size: 24rpx;
          color: #999;
          background-color: #f5f5f5;
          padding: 4rpx 16rpx;
          border-radius: 20rpx;
          margin-right: 10rpx;
          margin-bottom: 10rpx;
        }
        
        .goods-price-quantity {
          margin-top: 10rpx;
          display: flex;
          justify-content: space-between;
          align-items: center;
          
          .goods-price {
            font-size: 32rpx;
            color: #ff6700;
            font-weight: bold;
          }
          
          .goods-quantity {
            font-size: 26rpx;
            color: #999;
          }
        }
      }
    }
  }
}

/* 订单信息卡片 */
.order-info-card {
  background-color: #fff;
  margin: 20rpx;
  border-radius: 12rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
  
  .card-header {
    padding: 20rpx 30rpx;
    border-bottom: 1rpx solid #eee;
    
    .card-title {
      font-size: 28rpx;
      font-weight: bold;
      color: #333;
    }
  }
  
  .order-detail-list {
    padding: 0 30rpx;
    
    .order-detail-item {
      display: flex;
      justify-content: space-between;
      padding: 20rpx 0;
      border-bottom: 1rpx solid #f5f5f5;
      
      &:last-child {
        border-bottom: none;
      }
      
      .item-label {
        color: #666;
        font-size: 26rpx;
      }
      
      .item-value {
        color: #333;
        font-size: 26rpx;
        text-align: right;
      }
      
      .item-value-with-copy {
        display: flex;
        align-items: center;
        
        .copy-btn {
          font-size: 22rpx;
          color: #3c8ce7;
          background: none;
          border: 1rpx solid #3c8ce7;
          border-radius: 50rpx;
          padding: 0 20rpx;
          height: 44rpx;
          line-height: 44rpx;
          margin-left: 10rpx;
          
          &::after {
            border: none;
          }
        }
      }
    }
  }
}

/* 价格信息卡片 */
.price-card {
  background-color: #fff;
  margin: 20rpx;
  border-radius: 12rpx;
  padding: 20rpx 30rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
  
  .price-item {
    display: flex;
    justify-content: space-between;
    padding: 10rpx 0;
    font-size: 26rpx;
    
    .price-label {
      color: #666;
    }
    
    .price-value {
      color: #333;
    }
    
    .discount-value {
      color: #ff6700;
    }
    
    &.total-price {
      margin-top: 15rpx;
      padding-top: 20rpx;
      border-top: 1rpx dashed #eee;
      
      .price-label {
        font-weight: bold;
        color: #333;
      }
      
      .total-value {
        color: #ff6700;
        font-size: 34rpx;
        font-weight: bold;
      }
    }
  }
}

/* 底部操作栏 */
/* 加载动画 */
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100vh;
  width: 100%;
  background-color: #f5f5f5;
}

.loading-spinner {
  width: 60rpx;
  height: 60rpx;
  border-radius: 50%;
  border: 6rpx solid #f3f3f3;
  border-top: 6rpx solid #ff6700;
  animation: spin 1s linear infinite;
}

.loading-text {
  margin-top: 20rpx;
  color: #666;
  font-size: 28rpx;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.bottom-action-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  background-color: #fff;
  display: flex;
  justify-content: flex-end;
  padding: 20rpx 30rpx;
  box-sizing: border-box;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
  
  .action-btn {
    height: 70rpx;
    line-height: 70rpx;
    font-size: 28rpx;
    border-radius: 35rpx;
    padding: 0 30rpx;
    margin-left: 20rpx;
    
    &.contact-btn {
      color: #333;
      background-color: #f5f5f5;
      border: 1rpx solid #ddd;
    }
    
    &.pay-btn, &.confirm-btn {
      color: #fff;
      background-color: #ff6700;
      border: 1rpx solid #ff6700;
    }
    
    &.remind-btn, &.review-btn {
      color: #ff6700;
      background-color: #fff;
      border: 1rpx solid #ff6700;
    }
  }
}
</style>